<template>
  <a-spin :spinning="loading">
    <a-form ref="formRef" :model="form" :rules="rules" :labelCol="{ span: 6 }" @finish="handleSubmit"
      @finishFailed="handleSubmitFailed">
      <div class="botton-top-contrainer">
        <a-space :size="2">
          <a-button type="primary" html-type="submit">保存</a-button>
          <a-button @click="handleNew">新增</a-button>
          <a-button @click="handleCopy">复制</a-button>
          <a-button @click="handleGoList">列表</a-button>
          <a-button>导出</a-button>
        </a-space>
      </div>

      <a-card>

        <a-row>
          <a-col :span="6">
            <a-form-item ref="resourceAttribute" label="资源属性" name="resourceAttribute">
              <a-select v-model:value="form.resourceAttribute" placeholder="请选择资源属性" @change="handleChanged">
                <a-select-option :value="0">人力</a-select-option>
                <a-select-option :value="1">设备</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item ref="code" label="编码" name="code">
              <a-input v-model:value="form.code" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item ref="name" label="名称" name="name">
              <a-input v-model:value="form.name" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item ref="belongDepartmentName" label="归属部门" name="belongDepartmentName">
              <a-input-search v-model:value="form.belongDepartmentName" @search="handleSerachDepartment" readonly />
            </a-form-item>
          </a-col>

          <a-col :span="18">
            <a-form-item ref="remark" label="备注" name="remark" :labelCol="{ span: 2 }">
              <a-input v-model:value="form.remark" />
            </a-form-item>
          </a-col>
        </a-row>

        <JVxeTable keep-source resizable ref="resourceItemRef" :columns="itemColumns"
          :dataSource="form.basPreProcessResourceDefinitionItemList" :rowNumber="true" :rowSelection="true"
          :disabled="formDisabled" :toolbar="true">
          <template #associationCodeSlot="props">
            <a-input-search @search="handleAssociationCodeView(props.row)" placeholder="请选择资源"
              v-model:value="props.row.associationName"></a-input-search>
          </template>
          <template #useDepartmentNameSlot="props">
            <a-input-search @search="handleDepartNameView(props.row)" placeholder="请选择班组"
              v-model:value="props.row.useDepartmentName"></a-input-search>
          </template>
          <template #processNameSlot="props">
            <a-input-search @search="handleProcessNameView(props.row)" placeholder="请选择工艺"
              v-model:value="props.row.processManagementName"></a-input-search>
          </template>
        </JVxeTable>

        <DeviceSelectModel :multiple="true" @register="deviceRegister" @getSelectResult="handleDevicehanged" />
        <ProcessModal @register="processRegister" @getSelectResult="handleProcesshanged" />
        <DepartmentModal @register="departmentRegister" @getSelectResult="handleDepartChanged" />
        <workCenterListSelectModel @register="workCenterModal" @getSelectResult="handleWorkCenterValue" />
      </a-card>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick, unref, toRaw } from 'vue';
import { useModal } from '/@/components/Modal';
import { useRoute, useRouter } from 'vue-router'
import { JVxeTable } from '/@/components/jeecg/JVxeTable';
import { itemColumns, rules } from './data/columns';
import { Resource, ResourceItem } from './data'
import workCenterListSelectModel from '/@/views/components/workCenterListSelectModel.vue';
import ProcessModal from '/@/views/components/processManagementSelectModels.vue';
import { DepartmentModal } from '/@/views/system/depart/export/select'
import { saveOrUpdate, get, getItems } from './api';
import { message } from 'ant-design-vue';
import DeviceSelectModel from '/@/views/components/deviceSelectModel.vue';

const router = useRouter()
const loading = ref(false)
const route = useRoute()
const formRef = ref()
const form = ref<Resource>(new Resource())
const operatFormItem = ref<ResourceItem | null>(null)
const isUpdate = ref(!!route.query.id)
const formDisabled = ref(false);
const resourceItemRef = ref();
const departForItem = ref(false);

const [workCenterModal, { openModal: openWorkCenterModal }] = useModal();
const [departmentRegister, { openModal: openDepartModal }] = useModal();
const [processRegister, { openModal: openProcessModal }] = useModal();
const [deviceRegister, { openModal: openDeviceModal }] = useModal();

function handleSerachDepartment() {
  departForItem.value = false
  openDepartModal(true, {
    isUpdate: isUpdate.value,
    showFooter: true,
  })
}
function handleDepartChanged(options, values) {
  if (values && values.length > 0) {
    if (!departForItem.value && form.value) {
      form.value.belongDepartmentId = values[0]
      form.value.belongDepartmentName = options[0].label
    } else if (operatFormItem.value) {
      operatFormItem.value.useDepartmentId = values[0]
      operatFormItem.value.useDepartmentName = options[0].label
    }
  }
}
function handleDevicehanged(values, _options) {
  console.log(values)
  if (values && operatFormItem && operatFormItem.value) {

    const oldest = resourceItemRef.value.getTableData()

    operatFormItem.value.associationId = values[0].item.id ?? ""
    operatFormItem.value.associationCode = values[0].item.code ?? ""
    operatFormItem.value.associationName = values[0].item.name ?? ""

    operatFormItem.value.processManagementId = values[0].item.processManagementId ?? ""
    operatFormItem.value.processManagementName = values[0].item.processManagementName ?? ""

    operatFormItem.value.useDepartmentName = values[0].item.useDepartmentName ?? ""
    operatFormItem.value.useDepartmentId = values[0].item.useDepartmentId ?? ""

    const records: any[] = []
    for (let i = 1; i < values.length; i++) {
      const value = values[i]

      const matchs = oldest.filter(x=>x.associationId == value.item.id)
      if(matchs && matchs.length > 0) continue

      const record = {
        associationId: value.item.id ?? "",
        associationCode: value.item.code ?? "",
        associationName: value.item.name ?? "",
        processManagementId: value.item.processManagementId ?? "",
        processManagementName: value.item.processManagementName ?? "",
        useDepartmentName: value.item.useDepartmentName ?? "",
        useDepartmentId: value.item.useDepartmentId ?? "",
      }
      records.push(record)
    }
    resourceItemRef.value.addRows(records)
  }
}
function handleProcesshanged(value, _options) {
  if (operatFormItem.value) {
    operatFormItem.value.processManagementId = value[0].item.id
    operatFormItem.value.processManagementName = value[0].item.processName
  }
}
function handleProcessNameView(row: ResourceItem) {
  operatFormItem.value = row
  openProcessModal(true, {
    isUpdate: isUpdate.value,
    showFooter: true,
  });
}
function handleAssociationCodeView(row: ResourceItem) {
  operatFormItem.value = row
  if (form.value.resourceAttribute == 1) {
    openDeviceModal(true, {
      isUpdate: isUpdate.value,
      showFooter: true,
    })
  } else {
    openWorkCenterModal(true, {
      isUpdate: isUpdate.value,
      showFooter: true,
    });
  }

}

function handleDepartNameView(row: ResourceItem) {
  operatFormItem.value = row
  departForItem.value = true
  openDepartModal(true, {
    isUpdate: isUpdate.value,
    showFooter: true,
  })
}

function handleWorkCenterValue(value, _options) {
  if (value && operatFormItem.value) {
    console.log(value[0])

    operatFormItem.value.associationId = value[0].item.id ?? ""
    operatFormItem.value.associationCode = value[0].item.workCenterCode ?? ""
    operatFormItem.value.associationName = value[0].item.workCenterName ?? ""

    operatFormItem.value.processManagementId = value[0].item.processManagementId ?? ""
    operatFormItem.value.processManagementName = value[0].item.processManagementName ?? ""

    operatFormItem.value.useDepartmentName = value[0].item.belongingDepartment ?? ""
    operatFormItem.value.useDepartmentId = value[0].item.belongingDepartmentId ?? ""
  }
}
function handleChanged(e) {
  console.log(e)
}
async function handleSubmit() {
  try {
    var items = []
    var errors = await resourceItemRef.value.validateTable();
    console.log('errors', errors)
    if (!errors) {
      items = resourceItemRef.value.getTableData()
    } else {
      return
    }
    if (!items || items.length == 0) {
      throw new Error("资源列表不能为空")
    }

    form.value.basPreProcessResourceDefinitionItemList = items
    if (form.value && form.value.basPreProcessResourceDefinitionItemList) {
      loading.value = true
      saveOrUpdate(form.value, isUpdate.value).then(() => {
        if (isUpdate.value) handleLoad()
      }).finally(() => {
        loading.value = false
      })
    }
  } catch (err: any) {
    message.error(err.message)
  }
}
function handleSubmitFailed(errorInfo: any) {
  console.log(errorInfo)
}

function handleLoad() {
  const { id = "" } = route.query
  if (id) {
    loading.value = true
    const _form = ref(null)
    const _items = ref(null)
    const res = get({ id }).then(res => {
      _form.value = res
    })

    const items = getItems({ id }).then(res => {
      _items.value = res
    })

    Promise.all([res, items]).then(() => {
      loading.value = false
      form.value = toRaw(unref(_form))!
      form.value.basPreProcessResourceDefinitionItemList = toRaw(unref(_items))!
      console.log('form', form.value)
    })
  }
}
function handleNew() {
  isUpdate.value = false
  loading.value = true
  setTimeout(() => {
    form.value = new Resource()
    loading.value = false
  }, 500)

}
function handleCopy() {
  loading.value = true
  isUpdate.value = false
  form.value.id = null
  form.value.basPreProcessResourceDefinitionItemList = form.value.basPreProcessResourceDefinitionItemList.map((item) => {
    item.id = null
    return item
  })
  setTimeout(() => {
    loading.value = false
  }, 500)
}
function handleGoList() {
  router.push({
    name: 'plan-scheduling-feol-resource-index',
    query: {
      t: Date.now()
    }
  })
}
onMounted(() => {
  nextTick(() => { handleLoad() })
})

</script>

<style lang="less" scoped>
.botton-top-contrainer {
  padding: 10px 10px 10px 10px;
}
</style>
